package com.pan.interceptor;

import com.pan.annotation.LoginRequired;
import com.pan.excep.enume.ErrorCode;
import com.pan.excep.error.ControllerException;
import com.pan.tools.RedisTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Optional;
import java.util.function.Predicate;

@Component
public class CartInterceptor implements HandlerInterceptor {

    @Resource
    private RedisTools redisTools;



    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (! (handler instanceof HandlerMethod)){
            return false;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Boolean isLoginRequired =  handlerMethod.getMethod().isAnnotationPresent(LoginRequired.class);
        if (!isLoginRequired){
            return true;
        }
        LoginRequired loginRequired = handlerMethod.getMethod().getAnnotation(LoginRequired.class);
        String identity = loginRequired.value();
        Cookie[] cookies = request.getCookies();
        Predicate<Cookie> isTicketCookie = cookie -> cookie.getName().equals(identity+"Ticket");
        Optional<Cookie> optionalCookie = Arrays.stream(cookies).filter(isTicketCookie).findFirst();
        if (!optionalCookie.isPresent()){
            throw new ControllerException(ErrorCode.NOT_TICKET);
        }
        String ticket = optionalCookie.get().getValue();
        Boolean isLogin = redisTools.exists(identity+":"+ticket).getData();//.stringRedisTemplate.hasKey();
        if (isLogin){
            return true;
        }
        throw new ControllerException(ErrorCode.NOT_LOGIN);
    }
}
